package el

import (
	"aiAutoPilot/robot/utils"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/playwright-community/playwright-go"
	"log"
	"net/url"
	"text/template"
	"time"
)

const ARTICLE_DETAIL_URL string = "https://tbeanews.tbea.com/api/article/detail"
const LIST_MESSAGE_URL string = "https://ejia.tbea.com/im/rest/message/listMessage"
const BATCH_TICKET_URL string = "https://ejia.tbea.com/space/c/rest/cloudwork/ticket/batchticket"

type ListMessageReqForm struct {
	groupId  string
	userId   string
	newsType string
	count    string
	msgId    string
}

type ListMessageResp struct {
	Data struct {
		Count   int    `json:"count"`
		GroupId string `json:"groupId"`
		List    []struct {
			MsgType      int         `json:"msgType"`
			OpenStatus   interface{} `json:"openStatus"` // 使用interface{}以适应可能的空值
			FromUserId   string      `json:"fromUserId"`
			MsgId        string      `json:"msgId"`
			FromClientId string      `json:"fromClientId"`
			Content      string      `json:"content"`
			SendTime     string      `json:"sendTime"`
			ExtFields    []struct {
				DataKey string `json:"dataKey"`
				Data    []struct {
					Expr     string `json:"expr"`
					PersonId string `json:"personId"`
					Time     int64  `json:"time"` // 使用int64以适应时间戳
				} `json:"data"`
				DataEncoding string `json:"dataEncoding"`
			} `json:"extFields"`
			MsgLen           int         `json:"msgLen"`
			PhotoUrl         string      `json:"photoUrl"`
			FromUserXtUpTime interface{} `json:"fromUserXtUpTime"` // 使用interface{}以适应可能的空值
			SenderName       string      `json:"senderName"`
			Param            struct {
				MsgType       int  `json:"msgType"`
				TodoNotify    bool `json:"todoNotify"`
				Personal      int  `json:"personal"`
				UpdateTime    int  `json:"updateTime"`
				SensitiveFlag int  `json:"sensitiveFlag"`
				List          []struct {
					VerifyInterval int    `json:"verifyInterval"`
					AppID          string `json:"appid"`
					Name           string `json:"name"`
					Personal       int    `json:"personal"`
					Row            int    `json:"row"`
					SensitiveFlag  int    `json:"sensitiveFlag"`
					Text           string `json:"text"`
					NavBarFlag     int    `json:"navBarFlag"`
					ThumbUrl       string `json:"thumbUrl"`
					Title          string `json:"title"`
					URL            string `json:"url"`
				} `json:"list"`
			} `json:"param"`
			SourceMsgId      string `json:"sourceMsgId"` // 使用interface{}以适应可能的空值
			Company          string `json:"company"`
			InCurrentNetwork bool   `json:"inCurrentNetwork"`
			Department       string `json:"department"`
			Direction        int    `json:"direction"`
			Status           int    `json:"status"`
		} `json:"list"`
	} `json:"data"`
	Error   string `json:"error"`
	ErrCode int    `json:"errCode"`
	Success bool   `json:"success"`
}

type TbeaNewsRecord struct {
	SendTime string     `json:"sendTime"`
	MsgId    string     `json:"msgId"`
	Content  string     `json:"content"`
	List     []NewsItem `json:"list"`
}

type NewsItem struct {
	Id    string `json:"id"`
	Url   string `json:"url"`
	Title string `json:"title"`
}

type ArticleDetailResp struct {
	Code int    `json:"code"`
	Show int    `json:"show"`
	Msg  string `json:"msg"`
	Data struct {
		Click        int     `json:"click"`
		ID           int     `json:"id"`
		PID          string  `json:"pid"`
		CID          int     `json:"cid"`
		Title        string  `json:"title"`
		Desc         string  `json:"desc"`
		Abstract     string  `json:"abstract"`
		Image        string  `json:"image"`
		Author       string  `json:"author"`
		Content      string  `json:"content"`
		IsList       int     `json:"is_list"`
		IsShow       int     `json:"is_show"`
		IsTop        int     `json:"is_top"`
		IsAnonymous  int     `json:"is_anonymous"`
		AllowComment int     `json:"allow_comment"`
		CheckComment int     `json:"check_comment"`
		PersonCount  int     `json:"person_count"`
		CommentCount int     `json:"comment_count"`
		DiggCount    int     `json:"digg_count"`
		Sort         int     `json:"sort"`
		CreateTime   string  `json:"create_time"`
		UpdateTime   string  `json:"update_time"`
		DeleteTime   *string `json:"delete_time"`
		SendTime     *string `json:"send_time"`
		PublishTime  string  `json:"publish_time"`
		EjiaID       string  `json:"ejia_id"`
		FileName     string  `json:"fileName"`
		CreateID     int     `json:"create_id"`
		UpdateID     int     `json:"update_id"`
		DeleteID     int     `json:"delete_id"`
		IsDigg       bool    `json:"is_digg"`
		OpenID       string  `json:"openId"`
	} `json:"data"`
}

// 浏览器变量
var tbeaBrowser playwright.Browser = nil

type BatchTicktResponse struct {
	Success    bool              `json:"success"`
	Data       map[string]string `json:"data"`
	ServerTime int64             `json:"serverTime"`
}

type ShowNewsRequest struct {
	Title    string `json:"title"`
	Url      string `json:"url"`
	SendTime string `json:"sendTime"`
}

func clickNewsChatWindow(frame playwright.Frame) {
	fmt.Println("开始模拟点击操作")
	frame.Locator("#XT-621d2a1bc2dc21395abfdaba-XT-2bb8a866-d2a3-47da-bbad-8c63db21e9b6").Click()
	frame.WaitForLoadState()
}

func clickChatItem(frame playwright.Frame) {
	time.Sleep(1 * time.Second)
	frame.Locator(".news-li ")
	listitem, _ := frame.Locator(".news-li ").All()
	listitem[len(listitem)-1].Click()
	fmt.Println("完成chatitem 模拟点击操作")
}

func getBatchTicket(page playwright.Page) BatchTicktResponse {
	options := playwright.APIRequestContextPostOptions{
		Data:             nil,
		FailOnStatusCode: nil,
		Form: map[string]interface{}{
			"appids": "500000249",
		},
		Headers:           nil,
		IgnoreHttpsErrors: func() *bool { b := false; return &b }(),
		MaxRedirects:      nil,
		MaxRetries:        nil,
		Multipart:         nil,
		Params:            nil,
		Timeout:           nil,
	}

	resp, err := page.Request().Post(BATCH_TICKET_URL, options)
	if err != nil {
		fmt.Println(err)
	}
	text, errtext := resp.Text()
	if errtext != nil {
		fmt.Println(errtext)
	}

	var respJson BatchTicktResponse
	json.Unmarshal([]byte(text), &respJson)

	return respJson
}

func ListMessage(page playwright.Page, form ListMessageReqForm) playwright.APIResponse {

	options := playwright.APIRequestContextPostOptions{
		Data:             nil,
		FailOnStatusCode: nil,
		Form: map[string]interface{}{
			"groupId": form.groupId,
			"userId":  form.userId,
			"type":    form.newsType,
			"count":   form.count,
			"msgId":   form.msgId,
		},
		Headers:           nil,
		IgnoreHttpsErrors: func() *bool { b := false; return &b }(),
		MaxRedirects:      nil,
		MaxRetries:        nil,
		Multipart:         nil,
		Params:            nil,
		Timeout:           nil,
	}

	resp, err := page.Request().Post(LIST_MESSAGE_URL, options)
	if err != nil {
		log.Println(err)
	}

	return resp

}

func openNewsPage() playwright.Frame {
	pageUrl := "https://ejia.tbea.com"
	if tbeaBrowser == nil {
		tbeaBrowser = utils.StartBrowser()
	}

	page := utils.OpenPage(tbeaBrowser, pageUrl)

	utils.WaitForUrlMatch(page, "https://ejia.tbea.com/yzj-layout/home/")
	fmt.Println("页面加载完成")
	time.Sleep(2 * time.Second)

	locatorListItem := page.Locator("[data-app='im']")
	//fmt.Println(locatorListItem.GetAttribute("data-url"))
	locatorListItem.Click()
	time.Sleep(2 * time.Second)
	fmt.Println("完成模拟IM click操作")

	//还没加载
	//page.WaitForEvent("framenavigated")

	var imFrame playwright.Frame
	for _, frame := range page.Frames() {
		fmt.Println(frame.URL())
		if frame.URL() == "https://ejia.tbea.com/im/xiaoxi/" {
			imFrame = frame

		}
	}
	fmt.Println("完成消息iframe加载")
	time.Sleep(2 * time.Second)
	return imFrame

}

func getArticleDetail(page playwright.Page, articleId string) ArticleDetailResp {
	//fmt.Println("articleId=" + articleId)
	resp, err := page.Request().Get(ARTICLE_DETAIL_URL + "?id=" + articleId)
	if err != nil {
		log.Println(err)
	}

	text, err := resp.Text()
	if err != nil {
		log.Println(err)
	}
	//fmt.Println(text)

	var article ArticleDetailResp

	json.Unmarshal([]byte(text), &article)

	return article

}
func getNewsList(page playwright.Page, groupid string, month string) []TbeaNewsRecord {

	var sendReqCount int = 0

	newsList := []TbeaNewsRecord{}
	var nextMsgId string = ""
	for {

		reqForm := ListMessageReqForm{
			groupId:  groupid,
			userId:   "",
			newsType: "new",
			count:    "10",
			msgId:    nextMsgId,
		}
		if sendReqCount > 0 {
			reqForm.newsType = "old"
		}
		fmt.Println("开始发送请求....")
		fmt.Println(reqForm)
		resp := ListMessage(page, reqForm)
		text, err := resp.Text()
		//fmt.Println("收到响应......")
		//fmt.Println(text)

		if err != nil {
			log.Println(err)
		}
		//fmt.Println(text)
		var respJson ListMessageResp // 或者使用你期望的数据结构
		json.Unmarshal([]byte(text), &respJson)

		//fmt.Println(text)
		// 定义日期字符串的格式
		layout := "20060102"
		layout2 := "2006-01-02 15:04:05"
		queryMonth := month + "01"
		monthDate, err := time.Parse(layout, queryMonth)

		if err != nil {
			log.Println("日期解析失败%v", err)
		}

		var newRequestEndFlag bool = false

		for _, news := range respJson.Data.List {
			//fmt.Println("新闻日期:" + news.SendTime)
			newsRecord := TbeaNewsRecord{}

			dateSendTime, err := time.Parse(layout2, news.SendTime)

			if err != nil {
				log.Println("日期解析失败%v", err)
			}

			fmt.Println(dateSendTime, monthDate)
			if dateSendTime.Before(monthDate) {
				newRequestEndFlag = true
				continue
			}
			if err != nil {
				fmt.Println("日期解析失败%v", err)
			}

			for _, newsitem := range news.Param.List {
				parsedURL, _ := url.Parse(newsitem.URL)
				queryParams := parsedURL.Query()
				id := queryParams.Get("id")

				newsRecord.List = append(newsRecord.List, NewsItem{
					Url:   newsitem.URL,
					Title: newsitem.Title,
					Id:    id,
				})
			}

			newsRecord.Content = news.Content
			newsRecord.SendTime = news.SendTime
			newsRecord.MsgId = news.MsgId

			newsList = append(newsList, newsRecord)

		}

		if newRequestEndFlag {
			break
		}

		nextMsgId = respJson.Data.List[0].MsgId
		sendReqCount = sendReqCount + 1
	}
	return newsList
}

func addResultPopWindow(page playwright.Page, newsList []ShowNewsRequest) {

	popupStyle := `
		.popup {
			position: fixed;
			bottom: 20px;
			right: 20px;
			background: #f9f9f9;
			border: 1px solid #ccc;
			padding: 20px;
			border-radius: 5px;
			box-shadow: 0px 0px 10px rgba(0,0,0,0.1);
			z-index: 1000;
			display: block;
		}
		.popup-content {
			padding: 20px;
		}
		.close-btn {
			float: right;
			font-size: 25px;
			cursor: pointer;
		}
		.hidden {
			display: none;
		}

	`
	insertStyle := `
		(popupStyle) => {
			const style = document.createElement('style');
			style.textContent = popupStyle;
			document.head.appendChild(style);
		}
			
	`
	if _, err := page.Evaluate(insertStyle, popupStyle); err != nil {
		log.Fatalf("failed to evaluate: %v", err)
	}

	tplPopupHTML := `
	<style>
	  /* 设置链接默认颜色为蓝色 */
	  a {
		color: blue;
		text-decoration: none; /* 去除下划线 */
	  }
	
	  /* 鼠标悬停在链接上时的样式 */
	  a:hover {
		text-decoration: underline; /* 添加下划线 */
	  }
	
	  /* 表格样式 */
	  table {
		width: 100%;
		border-collapse: collapse; /* 合并边框 */
	  }
	
	  /* 表格单元格样式 */
	  th, td {
		border: 1px solid #ddd; /* 单元格边框 */
		padding: 8px; /* 内边距 */
		text-align: left; /* 文本左对齐 */
	  }
	
	  /* 表头样式 */
	  th {
		background-color: #f2f2f2; /* 背景颜色 */
	  }
	</style>
	<div id="popup" class="popup">
		<div><button id='digbutton' style='background-color: blue; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;''>一键点赞</button></div>
		<div class="popup-content">
			<span class="close-btn">&times;</span>
			<table>
			  <tr>
				<th>未读新闻</th><th>发布时间</th>
			  </tr>
			<tr>
				{{range .Items}}
					<tr><td><a href="{{.Url}}" target="_blank">{{.Title}}</a></td><td>{{.SendTime}}</td></tr>
				{{end}}
			</tr>
			
		</div>
	</div>

	`
	// 定义模板数据
	popupdata := struct {
		Items []ShowNewsRequest
	}{
		Items: newsList,
	}
	var buf bytes.Buffer
	t, err := template.New("popupDiv").Parse(tplPopupHTML)
	if err != nil {
		log.Fatal(err)
	}
	err = t.Execute(&buf, popupdata)
	popupDivHtml := buf.String()

	//sfmt.Println("-=---------------------")
	//fmt.Println(popupDivHtml)
	insertScript := `
		(popwin) => {
			document.body.insertAdjacentHTML('beforeend', popwin);	

			document.querySelector('.close-btn').addEventListener('click', function() {
				document.getElementById('popup').classList.add('hidden');
			});

			document.getElementById('digbutton').addEventListener('click', function() {
				console.log("点赞按钮被点击了！"); 
				var xhr = new XMLHttpRequest();
				xhr.open('POST', 'https://tbeanews.tbea.com/api/article/addDigg', true);
				// 设置请求头部，例如设置发送 JSON 数据
				xhr.setRequestHeader('Content-Type', 'application/json');
				
				// 设置响应类型（如果需要）
				xhr.responseType = 'json';

				xhr.onload = function () {
				  if (xhr.status >= 200 && xhr.status < 300) {
					// 请求成功，可以使用响应数据 xhr.response
					console.log(xhr.response);
				  } else {
					// 请求出错
					console.error(xhr.statusText);
				  }
				};
				
				// 定义当请求失败时的回调函数
				xhr.onerror = function () {
				  console.error('Request error...');
				};
				
				// 发送请求，附带一些数据
				xhr.send(JSON.stringify({ id: '3980' }));

				console.log("发送！"); 

			});



		}
			
	`

	// 注入弹窗到页面
	if _, err := page.Evaluate(insertScript, popupDivHtml); err != nil {
		log.Fatalf("failed to evaluate: %v", err)
	}

	fmt.Println("结果弹窗生成")

}

func RunTbeaWebRobot(action string, month string) {

	imFrame := openNewsPage()

	clickNewsChatWindow(imFrame)
	time.Sleep(2 * time.Second)

	clickChatItem(imFrame)

	time.Sleep(2 * time.Second)
	postRequest := []ShowNewsRequest{}

	if action == "checkNews" {
		TbeaNewsRecordList := getNewsList(imFrame.Page(), "XT-621d2a1bc2dc21395abfdaba-XT-2bb8a866-d2a3-47da-bbad-8c63db21e9b6", month)

		for _, record := range TbeaNewsRecordList {
			for _, newsitem := range record.List {

				articleDetail := getArticleDetail(imFrame.Page(), newsitem.Id)
				if articleDetail.Data.IsDigg == false {
					fmt.Println(newsitem.Id, newsitem.Title, newsitem.Url)
					postRequest = append(postRequest, ShowNewsRequest{
						Title:    newsitem.Title,
						Url:      newsitem.Url,
						SendTime: record.SendTime,
					})
				}
				break
			}
		}

		xtNewsRecordList := getNewsList(imFrame.Page(), "XT-621d2a1bc2dc21395abfdaba-XT-83d773eb-d606-4049-8ff4-937615f23dc5", month)
		for _, record := range xtNewsRecordList {
			for _, newsitem := range record.List {

				articleDetail := getArticleDetail(imFrame.Page(), newsitem.Id)
				if articleDetail.Data.IsDigg == false {
					fmt.Println(newsitem.Id, newsitem.Title, newsitem.Url)
					postRequest = append(postRequest, ShowNewsRequest{
						Title:    newsitem.Title,
						Url:      newsitem.Url,
						SendTime: record.SendTime,
					})
				}
				break
			}
		}

	}

	addResultPopWindow(imFrame.Page(), postRequest)
	result, err := imFrame.Page().Evaluate("console.log('');")
	if err != nil {
		log.Println(err)
	}
	fmt.Println(result)
	//jsonReq, err := json.Marshal(postRequest)

	//if err != nil {
	//	log.Println(err)
	//}
	//postResult("http://127.0.0.1:8080/tbeanew/newslist", jsonReq)

	fmt.Println("完成信息处理.....")

	time.Sleep(12000 * time.Second)

}
